<template>
  <a-modal title="分步对话框" :width="700" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- type -->
        <a-form-item label="菜单名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group
            label="类型"
            @change="chanType"
            v-decorator="['type', { rules: [{ required: true }], initialValue: 0 }]"
          >
            <a-radio-button :value="0">菜单</a-radio-button>
            <a-radio-button :value="1">按钮</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <!-- title  -->
        <a-form-item label="菜单名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['title', { rules: [{ required: true }] }]" />
        </a-form-item>
        <a-form-item label="上级菜单" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-tree-select
            v-decorator="['pid', { rules: [{ required: true }], initialValue: '0' }]"
            showSearch
            :treeData="treeMenuList"
            :treeDataSimpleMode="treeDataSimpleMode"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="选择菜单作为上级菜单"
            treeNodeFilterProp="title"
            @change="handleTreeSelectChange"
          />
        </a-form-item>
        <!-- routerName -->
        <a-form-item label="路由名称" v-if="formData.type" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['routerName', { rules: [{ required: formData.type }] }]" />
        </a-form-item>
        <!-- redirect -->
        <a-form-item label="重定向" v-if="formData.type" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['redirect', {}]" />
        </a-form-item>
        <!-- components -->
        <a-form-item label="组件" v-if="formData.type" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-auto-complete
            v-decorator="['component']"
            :dataSource="layoutComponentsMap"
            style="width: 200px"
            placeholder="组件名"
          />
        </a-form-item>
        <!-- sort -->
        <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number v-decorator="['sort', { initialValue: 0 }]" :precision="0" :min="0" :max="99999" />
        </a-form-item>
        <!-- permissions -->
        <a-form-item label="权限标识" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['permissions', {}]" />
        </a-form-item>
        <!-- icon  -->
        <a-form-item label="图标" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <icon-selector-form
            v-decorator="['icon', { initialValue: '', rules: [{ validator: validateIcon }] }]"
            @change="handleSelectIcon"
            ref="iconSelector"
          />
        </a-form-item>
        <a-form-item label="高级设置" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a @click="toggleAdvanced">
            {{ advanced ? '收起' : '展开' }}
            <a-icon :type="advanced ? 'up' : 'down'" />
          </a>
        </a-form-item>
        <div v-show="advanced">
          <!--   hidden -->
          <a-form-item label="在左侧菜单中隐藏" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch
              v-decorator="['hidden', { valuePropName: 'checked' }]"
              @change="toggleHidden"
              checkedChildren="是"
              unCheckedChildren="否"
            />
          </a-form-item>
          <!--   hideChildrenInMenu -->
          <a-form-item label="隐藏子路由" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch
              v-decorator="['hideChildrenInMenu', { valuePropName: 'checked' }]"
              @change="toggleHidden"
              checkedChildren="是"
              unCheckedChildren="否"
            />
          </a-form-item>
          <!--   target -->
          <a-form-item label="菜单打开方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-radio-group v-decorator="['target', { initialValue: null }]">
              <a-radio-button :value="null">默认</a-radio-button>
              <a-radio-button value="_self">同框架</a-radio-button>
              <a-radio-button value="_blank">新窗口</a-radio-button>
              <a-radio-button value="_parent">父框架</a-radio-button>
              <a-radio-button value="_top">整个窗口</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
    <template slot="footer">
      <a-button key="cancel" @click="handleCancel">取消</a-button>
      <a-button key="forward" :loading="confirmLoading" type="primary" @click="handleCommit">确定</a-button>
    </template>
  </a-modal>
</template>

<script>
import IconSelectorForm from '@/components/IconSelector/IconSelectorForm'
import { saveMenu, getMenuList } from '@/api/sys'
import pick from 'lodash.pick'

const formFields = [
  'pid',
  'type',
  'title',
  'routerName',
  'redirect',
  'component',
  'sort',
  'permissions',
  'hidden',
  'hideChildrenInMenu',
  'target',
  'icon'
]

export default {
  name: 'MenuFormModal',
  components: {
    IconSelectorForm
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      visible: false,
      confirmLoading: false,
      mdl: {},
      advanced: true, // 高级设置 展开/收起
      form: this.$form.createForm(this),
      formData: {
        id: 0,
        type: false, // false: 显示菜单隐藏按钮的表单
        icon: ''
      },
      // loadMenuList: parameter => {
      //   return getMenuList(Object.assign(parameter, { type: 0 }))
      //     .then(res => {
      //       const childrenList = []
      //       listToTreeSelectData(res.data, childrenList, '0')
      //       console.log('childrenList', childrenList)
      //       res.data = childrenList
      //       return res
      //     })
      // },
      treeMenuList: [],
      layoutComponentsMap: ['PageView', 'RouteView', 'BlankLayout', 'UserLayout'],
      treeDataSimpleMode: { id: 'id', pId: 'pid', rootPId: '-1' }
    }
  },
  methods: {
    add() {
      this.visible = true
      this.formData.id = ''
      this.getMenuList()
      this.$nextTick(() => {
        this.form.resetFields()
        // console.log(this.form)
      })
    },
    edit(record) {
      this.visible = true
      this.getMenuList()
      const {
        form: { setFieldsValue }
      } = this
      const fieldsValue = pick(record, formFields)
      const { id, type } = record
      this.formData.id = id
      this.formData.type = type === 0
      this.$nextTick(() => {
        console.log(fieldsValue)
        setFieldsValue(fieldsValue)
      })
    },
    handleCommit(step) {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        values.id = this.formData.id
        console.log('errors:', errors, 'val:', values)
        console.log('commit icon:', values.icon)
        if (!errors) {
          console.log('values:', values)
          saveMenu(values).then(res => {
            console.log(res)
            if (res.code === 0) {
              this.visible = false
              this.confirmLoading = false
              this.$emit('ok')
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    backward() {
      this.currentStep--
    },
    handleCancel() {
      // clear form & currentStep
      this.visible = false
    },
    // 切换菜单类型
    chanType(e) {
      console.log(`checked = ${e.target.value}`)
      this.formData.type = e.target.value === 0
    },
    // 高级设置展开/关闭
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // 是否在菜单导航中隐藏
    toggleHidden(checked, e) {
      console.log(e.target.value)
    },
    handleTargetChange(e) {
      //
    },
    // icon
    handleSelectIcon(icon) {},
    validateIcon(rule, value, callback) {
      if (value === '') {
        callback()
      }
      if (!this.$refs.iconSelector.validateIcon(value)) {
        callback(new Error('图标库中无此图标'))
      }
      callback()
    },
    // setFieldsValue (options) {
    //   console.log(options)
    //   const { form: { setFieldsValue } } = this
    //   setFieldsValue(options)
    // }
    getMenuList() {
      getMenuList({ type: 0 }).then(res => {
        const childrenList = []
        const rootMenu = {
          id: '0',
          pid: '-1',
          title: '根级菜单',
          value: '0',
          children: []
        }
        res.data.push(rootMenu)
        this.listToTreeSelectData(res.data, childrenList, '-1')
        console.log('childrenList', childrenList)
        this.treeMenuList = childrenList
      })
    },
    listToTreeSelectData(list, tree, rootPid) {
      list.forEach(item => {
        const { id, pid, title } = item
        // 判断是否为父级菜单
        if (pid === rootPid) {
          const child = {
            id,
            pid,
            title: this.$t(title),
            value: id,
            children: []
          }
          // 迭代 list， 找到当前菜单相符合的所有子菜单
          this.listToTreeSelectData(list, child.children, id)
          // 删掉不存在 children 值的属性
          if (child.children.length <= 0) {
            delete child.children
          }
          // 加入到树中
          tree.push(child)
        }
      })
    },
    handleTreeSelectChange(value, node, extra) {
      console.log(this.form.getFieldsValue(['pid']))
      console.log(value)
    }
  }
}
</script>
